<template>
  <div class="areaTimeStatistics">
    <x-header class="header" :left-options="{showBack: showHeaderBack,preventGoBack:true}" @on-click-back="goToPage" ref="header">区域时段统计</x-header>
    <div class="topHolder"></div>
    <card class="gridDisplay">
      <div class="card-padding" slot="content" style="padding-top: 0;">
        <div class="filterArea dateFilter">
          <group-title style="text-align: center;">当前显示日期：{{choosenDate}}<br/></group-title>
          <x-button :show-loading="loadingStatus" :disabled="loadingStatus" @click.native="changeDate(1)" class="inlineBtn">今日</x-button>
          <x-button :show-loading="loadingStatus" :disabled="loadingStatus" @click.native="changeDate(2)" class="inlineBtn">昨日</x-button>
          <a v-if="loadingStatus" class="datePicker"><i class="iconfont icon-rilicalendar107"></i></a>
          <datetime v-else v-model="choosenDate" :start-date="startDate" :end-date="endDate" @on-confirm="changeDate(0)" class="datePicker">
            <i class="iconfont icon-rilicalendar107"></i>
          </datetime>
        </div>
      </div>
    </card>
    <group title="区域时段营业额：">
      <div style="height: 20px;"></div>
      <canvas height="260" class="noselect" ref="lineChart"></canvas>
      <div style="height: 20px;"></div>
    </group>
    <card>
      <div class="card-padding" slot="content">
        <div class="filterArea">
          <div class="filterItem"><x-button @click.native="showTimeZone = true" type="default" v-html="timeZoneText" :show-loading="loadingStatus" :disabled="loadingStatus" class="inlineBtn popPickerBtn"></x-button>&nbsp;房台区域/类型明细：</div>
        </div>
        <popup-picker @on-hide="pupupPickerFunc" :show.sync="showTimeZone" :show-cell="false" :data="timeZone" :columns="1" v-model="choosenTimeZone" ref="timeZone" class="btn_popup-picker"></popup-picker>
      </div>
    </card>
    <group class="tableDisplay">
      <x-table :cell-bordered="false">
        <thead>
        <tr style="background-color: #F7F7F7">
          <th width="30%">房台类型</th>
          <th width="30%">房台区域</th>
          <th width="40%">营业额</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item,index) in turnList" :key="index">
          <td v-html="item.ROOM_PLATFORM_TYPE"></td>
          <td v-text="item.AREA"></td>
          <td v-text="'¥ ' + formatCurrency(item.value) + '元'"></td>
        </tr>
        <tr v-if="turnList.length <= 0">
          <td colspan="3">
            <div class="listNoItem">暂无区域时段明细</div>
          </td>
        </tr>
        </tbody>
      </x-table>
    </group>
    <group :title="choosenTimeZone + '时段营业额明细：'">
      <canvas height="260" class="noselect" ref="pieChart"></canvas>
      <div style="height: 30px;"></div>
    </group>
  </div>
</template>

<script>
  import F2 from '@antv/f2/build/f2-all.js'
  import {XButton, Card, Group, Datetime, GroupTitle, PopupPicker, XTable, dateFormat, numberComma } from 'vux'
  import {getAreaTimeTurnover,getBusinessHours} from "../../api";
  import {message,toDecimal2} from "../../common/util";

  export default {
    name:'areaTimeStatistics',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        loadingStatus:true,
        originalData:{},
        choosenDate:dateFormat(new Date(), 'YYYY-MM-DD'),
        startDate:'2019-01-01',
        endDate:dateFormat(new Date(), 'YYYY-MM-DD'),
        lineChartData:[],
        lineChart:{},
        showTimeZone:false,
        timeZone:[],
        timeZoneText:'',
        choosenTimeZone:[],
        turnList:[],
        pieChartData:[],
        pieChart:{},
        pieChartHeight:250
      }
    },
    components:{
      XButton,
      Card,
      Group,
      Datetime,
      GroupTitle,
      PopupPicker,
      XTable
    },
    computed:{
      businessHours:{
        get(){
          return this.$store.getters.getBusinessHours
        },
        set(value){
          this.$store.commit('updateBusinessHours',value)
        }
      }
    },
    methods:{
      goToPage(){
        this.$router.push({path:'/'})
      },
      formatCurrency(number){
        return numberComma(toDecimal2(number))
      },
      changeDate(value){
        console.log(value)
        switch (value) {
          case 1:this.choosenDate = dateFormat(new Date(), 'YYYY-MM-DD');break;
          case 2:this.choosenDate = dateFormat(new Date().setDate(new Date().getDate()-1), 'YYYY-MM-DD');break;
          default: break;
        }
        console.log(this.choosenDate)
        this.changeLineChartData()
      },
      refreshPage(params){
        this.loadingStatus = true
        this.lineChartData = []
        getAreaTimeTurnover(this.choosenDate).then((res)=>{
          if(res.status == 'success'){
            this.originalData = res.data
            for(let item of res.data.areaTime){
              this.lineChartData.push({
                type: item.AREA + '（' + item.ROOM_PLATFORM_TYPE + '）',
                time: item.time,
                value: item.value
              })
            }
          }else if(res.status == 'error') {
            message({message:res.msg,type:'error'})
            console.log('getAreaTimeTurnover error info:', res.msg)
          }
          if(params && params.callback && typeof params.callback == 'function')params.callback(res.status)
        }).catch((err)=>{console.log('getAreaTimeTurnover catch info:',err)})
      },
      initLineChart(){
        const windowWidth = window.innerWidth
        this.lineChart = new F2.Chart({
          id: this.$refs.lineChart,
          width: windowWidth,
          pixelRatio: window.devicePixelRatio
        });
        this.lineChart.source(this.lineChartData, {
          'time': {
            tickCount: 6
          }
        });
        // 设置图例居中显示
        this.lineChart.legend({
          align: 'center',
          itemWidth: null // 图例项按照实际宽度渲染
        });
        // tooltip 与图例结合
        this.lineChart.tooltip({
          showCrosshairs: true
        });
        this.lineChart.line().position('time*value').color('type').style('type', {
          lineDash: function lineDash(val) {
            if (val === 'Total') {
              return [1, 4];
            }
            return null;
          }
        });
        this.lineChart.point().position('time*value').color('type');
        this.lineChart.render();
      },
      changeLineChartData(){
        this.refreshPage({callback:(status)=>{
            if(status == 'success') {
              this.lineChart.changeData(this.lineChartData)
              this.changePieChartData()
            }
            this.loadingStatus = false
          }})
      },
      initPieChart(){
        const windowWidth = window.innerWidth
        const windowHeight = window.innerHeight
        this.pieChart = new F2.Chart({
          id: this.$refs.pieChart,
          width: windowWidth,
          height: this.pieChartHeight ? this.pieChartHeight : (windowWidth > windowHeight ? (windowHeight - 54) : windowWidth * 0.707),
          pixelRatio: window.devicePixelRatio
        });
        this.pieChart.source(this.pieChartData)
        this.pieChart.coord('polar', {
          transposed: true,
          innerRadius: 0.4,
          radius: 0.75
        });
        this.pieChart.axis(false);
        this.pieChart.legend({
          position: 'bottom',
          align: 'center',
          itemMarginBottom: 20
        });
        this.pieChart.tooltip(false);
        this.pieChart.guide().html({
          position: ['50%', '50%'],
          html: '<div style="width: 80px;height: 20px;text-align: center;line-height: 20px;font-size: 0.9rem" id="textContent">营业额明细</div>'
        });
        // 配置文本饼图
        this.pieChart.pieLabel({
          sidePadding: 15,
          label1: function label1(data) {
            return {
              text: data.memo,
              fill: '#808080'
            };
          },
          label2: function label2(data) {
            return {
              fill: '#000000',
              text: '¥' + data.amount + '元'
            };
          }
        });
        this.pieChart.interval().position('const*ratio').color('memo', ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14', '#F04864', '#8543E0', '#3436C7', '#223273']).adjust('stack');
        this.pieChart.render();
        // 绘制内阴影
        var frontPlot = this.pieChart.get('frontPlot');
        var coord = this.pieChart.get('coord'); // 获取坐标系对象
        frontPlot.addShape('sector', {
          attrs: {
            x: coord.center.x,
            y: coord.center.y,
            r: coord.circleRadius * coord.innerRadius * 1.2, // 全半径
            r0: coord.circleRadius * coord.innerRadius,
            fill: '#000',
            opacity: 0.15
          }
        });
        this.pieChart.get('canvas').draw();
      },
      refreshList(){
        this.turnList = []
        this.pieChartData = []
        this.pieChartHeight = 250
        if(JSON.stringify(this.originalData) != '{}'){
          for(let item of this.originalData.areaTime){
            if(item.time == this.choosenTimeZone[0]){
              this.turnList.push({
                AREA:item.AREA,
                ROOM_PLATFORM_TYPE:item.ROOM_PLATFORM_TYPE,
                value:item.value
              })
            }
          }
          this.originalData.timeDetail.forEach((detailItem) => {
            if(detailItem[0] == this.choosenTimeZone[0]){
              let total = 0
              for(let item of detailItem[1]){
                total += parseFloat(item.value)
              }
              for(let item of detailItem[1]){
                this.pieChartData.push({amount: parseFloat(item.value),ratio: parseFloat(item.value)/total,memo: item.name,const: 'const'})
              }
              this.pieChartHeight += this.pieChartData.length * 20
            }
          })
        }
      },
      changePieChartData(){
        this.refreshList()
        this.pieChart.changeData(this.pieChartData)
      },
      reInitChart(){
        this.lineChart.destroy()
        this.pieChart.destroy()
        this.initLineChart()
        this.initPieChart()
      },
      pupupPickerFunc(closeType){
        if(closeType){
          this.changeTimeZoneText()
          this.changePieChartData()
        }
      },
      changeTimeZoneText(){
        this.timeZoneText = this.$refs.timeZone&&this.$refs.timeZone.getNameValues().replace(/ /g,' / ')+'<i class=\'iconfont icon-xiangxia2\'></i>'
      }
    },
    mounted(){
      return new Promise(resolve => {
        if(JSON.stringify(this.businessHours) == '{}')
          getBusinessHours().then((res)=>{
            if(res.status == 'success'){
              this.businessHours = res.data
              resolve()
            }else if(res.status == 'error') {
              message({message:res.msg,type:'error'})
              console.log('getBusinessHours error info:', res.msg)
            }
          }).catch((err)=>{console.log('getBusinessHours catch info:',err)})
        else resolve()
      }).then(()=>{
        for(var i = Number(this.businessHours.open.split(":")[0]); i <= 23; i++){
          this.timeZone.push({name: (i < 10?'0' + i:i) + ':00' + "时段",value: (i < 10?'0' + i:i) + ':00'})
        }
        for(var i = 0; i <= Number(this.businessHours.close.split(":")[0]); i++){
          this.timeZone.push({name: (i < 10?'0' + i:i) + ':00' + "时段",value: (i < 10?'0' + i:i) + ':00'})
        }
        setTimeout(()=>{this.changeTimeZoneText()},200)
        this.choosenTimeZone.push(this.timeZone[0].value)
        this.refreshPage({callback:(status)=>{
            if(status == 'success'){
              this.initLineChart()
              this.refreshList()
              this.initPieChart()
              window.addEventListener('resize', this.reInitChart)
            }
            this.loadingStatus = false
            this.$store.commit('updateLoadingStatus',{isLoading:false})
          }})
      })
    },
    beforeDestroy () {
      window.removeEventListener('resize', this.reInitChart)
      this.lineChart.destroy()
      this.pieChart.destroy()
    }
  }
</script>

<style lang="scss">
  .areaTimeStatistics{
    .gridDisplay{
      .filterArea{
        &.dateFilter{
          margin-bottom: 0.5rem;
          .datePicker{
            float: right;padding: 0;
            &.weui-cell:before{border-top: none;}
            i{font-size: 2rem;color:#535353;}
          }
        }
        .filterItem{margin-top: 0.5rem;}
      }
    }
    .tableDisplay{
      .vux-no-group-title{margin-top: 0;}
    }
    .noselect {
      -webkit-touch-callout: none; /* iOS Safari */
      -webkit-user-select: none; /* Safari */
      -khtml-user-select: none; /* Konqueror HTML */
      -moz-user-select: none; /* Firefox */
      -ms-user-select: none; /* Internet Explorer/Edge */
      user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
    }
  }
</style>
